<?php

namespace App\Models\Traits;

use App\Models\GoldRecord;
use App\Models\User;
use App\Models\GoldRound;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;
use Carbon\Carbon;

trait GoldProductCacheTrait
{
	public static function sCacheKey($pid, $rid): string
	{
		return "gold_product_{$pid}_in_round_{$rid}";
	}

	public static function sGetCache($pid, $rid)
	{
		return Redis::hGetAll(self::sCacheKey($pid, $rid));
	}

	public static function sIsInCache($pid, $rid)
	{
		return Redis::exists(self::sCacheKey($pid, $rid));
	}

	public static function sBuyFromCache($uid, $pid, $rid)
	{

		//Redis::transaction(function () use ($uid, $pid, $rid) {
			self::sAddToSoldCache($pid, $rid);
			self::sDelFromAliveCache($pid, $rid);
			User::sAddRecordToUnpaidCache($uid, self::sCacheKey($pid, $rid));
		//});
	}

	public static function sAddToAliveCache($pid, $rid)
	{
        Redis::sAdd(GoldRound::sAliveGoldProductsCacheKey($rid), $pid);
	}

	public static function sDelFromAliveCache($pid, $rid)
	{
		Redis::sRem(GoldRound::sAliveGoldProductsCacheKey($rid), $pid);
	}

	public static function sIsInAliveCache($pid, $rid): bool
	{
		return Redis::sismember(GoldRound::sAliveGoldProductsCacheKey($rid), $pid);
	}

	public static function sAddToSoldCache($pid, $rid)
	{
		Redis::sAdd(GoldRound::sSoldGoldProductsCacheKey($rid), $pid);
	}

	public static function sDelFromSoldCache($pid, $rid)
	{
		Redis::sRem(GoldRound::sSoldGoldProductsCacheKey($rid), $pid);
	}

	public static function sIsInSoldCache($pid, $rid)
	{
		return Redis::sismember(GoldRound::sSoldGoldProductsCacheKey($rid), $pid);
	}



	/*==================================================================================================================*/



	public function cacheKey(): string
	{
		$round = $this->goldRound;
		return self::sCacheKey($this->id, $round->id);
	}

	public function closeFromCache()
	{
		//Redis::transaction(function () {
			$this->delFromSoldCache();
			$this->addToAliveCache();
		//});
	}

	public function addToCache()
	{
        /**
         * @var GoldRecord $lastRecord
         */
        $lastRecord = $this->lastValidRecord();
        $lastSplitRecord = $this->lastSplitRecord();

        $resellUserAvatar = $resellUserName = $resellUserId = $resellRecordCacheId = $lastCreateTime =  '' ;
        $resellAt = Carbon::now();

        if ($lastRecord) {
            $user = $lastRecord->user;
            $resellUserAvatar = img_path($user->avatar);
            $resellUserName = $user->name;
            $resellUserId = $user->id;
            $resellRecordCacheId = $lastRecord->cache_id;
            $lastCreateTime = !empty($lastRecord->to_resell_applied_at) ? strtotime("+4 days", strtotime($lastRecord->to_resell_applied_at)) : '';
            $resellAt = $lastRecord->to_resell_applied_at;
        }elseif($lastSplitRecord){
        	$user = $lastSplitRecord->user;
            $resellUserAvatar = img_path($user->avatar);
            $resellUserName = $user->name;
            $resellUserId = $user->id;
            $resellRecordCacheId = $lastSplitRecord->splitRecord->cache_id;
            $lastCreateTime = strtotime("+3 days", strtotime($lastSplitRecord->started_at));
        }

        if($lastCreateTime){
        	
        	if(time()>$lastCreateTime){
        		return false;

        	} 
        }

        if(empty($resellAt)){
			return false;

        }
      

		$data = [
			'id' => $this->id,
			'gold_round_id' => $this->gold_round_id,
			'all_price_today' => (string)$this->allPriceToday(),
			'net_price_today' => (string)$this->allPriceToday(),
			//'cash_price_today' => (string)$this->cashPriceToday(),
			'gold_beans_today' => (string)$this->goldBeansToday(),
			'all_price_next' => (string)$this->allPriceNext(),

            'resell_user_avatar' => $resellUserAvatar,
            'resell_user_name' => $resellUserName,
            'resell_user_id'   => $resellUserId,
            'resell_record_cache_id'   => $resellRecordCacheId,

			'all_rounds' => $this->allRound(),
            'round' => $this->currentRound(),
			'is_last_round' => $this->isLastRound(),
			'will_be_last_round' => $this->willBeLastRound(),

			'splits_all_count' => $this->splitsAllCount(),
			'splits_all_money' => (string)$this->splitsAllMoney(),

			'product_title' => $this->goldSeed->product->title,
			'product_cover' => $this->goldSeed->product->cover_url,
			'product_market_price' => $this->goldSeed->product->price_market,
			'product_id' => $this->goldSeed->product_id,

			'today_opened_at' => (string)$this->goldRound->today_opened_at,
			'today_started_at' => (string)$this->goldRound->today_started_at,
			'today_ended_at' => (string)$this->goldRound->today_ended_at,

            'created_at' => (string)$this->created_at,
            'voucher' => '',
		];

		if($data['will_be_last_round']){

			$data['gold_beans_today'] = (string)$this->goldBeansSplitToday();
			$data['all_price_next'] = $data['splits_all_money'];

		}

		Redis::hMset($this->cacheKey(), $data);
	}

	public function delFromCache()
	{
		Redis::del($this->cacheKey());
	}

	public function delLockCache()
	{
		Redis::del('buy_gold_product_'.$this->id);
	}

	public function addToAliveCache()
	{
		$round = $this->goldRound;
		$lastRecord = $this->lastValidRecord();
        $lastSplitRecord = $this->lastSplitRecord();
        $lastCreateTime = $resellRecordCacheId  = $resellUserId = '';
        $resellAt = Carbon::now();
        if ($lastRecord) {
        	 $resellRecordCacheId = $lastRecord->cache_id;


            $lastCreateTime = !empty($lastRecord->to_resell_applied_at) ? strtotime("+3 days", strtotime($lastRecord->to_resell_applied_at)) : '';
             $resellAt = $lastRecord->to_resell_applied_at;
             $resellUserId  = $lastRecord->user_id;

        }elseif($lastSplitRecord){
        	$resellRecordCacheId = $lastSplitRecord->splitRecord->cache_id;
            $lastCreateTime = strtotime("+3 days", strtotime($lastSplitRecord->started_at));
            $resellUserId  = $lastSplitRecord->user_id;
        }
        if(empty($resellAt)){
			return false;

        }

        $zjrIds = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,927];
        if($lastCreateTime){
        	
        	if(time()>$lastCreateTime){
        		Redis::hMset($resellRecordCacheId,['is_ending'=>true]);
        		return false;

        	} 
        }


		self::sAddToAliveCache($this->id, $round->id);
	}

	public function isInAliveCache(): bool
	{
		$round = $this->goldRound;
		return self::sIsInAliveCache($this->id, $round->id);
	}

	public function delFromAliveCache()
	{
		$round = $this->goldRound;
		self::sDelFromAliveCache($this->id, $round->id);
	}

	public function addToSoldCache()
	{
		$round = $this->goldRound;
		self::sAddToSoldCache($this->id, $round->id);
	}

	public function isInSoldCache(): bool
	{
		$round = $this->goldRound;
		return self::sIsInAliveCache($this->id, $round);
	}

	public function delFromSoldCache()
	{
		$round = $this->goldRound;
		self::sDelFromSoldCache($this->id, $round->id);
	}
}
